#!/usr/bin/env python
# -*- coding: utf-8 -*-



import logging
from typing import List
import numpy as np
from datetime import datetime, timedelta
import copy

from apps.models.data_model import Data

class DataAlignment:
    """
    数据对齐工具

    @Author: kindey
    @Date: 2025/6/18
    @Description:
    """
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)

    @staticmethod
    def reacquisition_by_time(
            source_dev_data: List[Data]
            , start_time: datetime
            , end_time: datetime
            , time_interval: timedelta
    ):
        """
        使用重采法按时间间隔对齐数据
        :param source_dev_data 原数据
        :param start_time 起始时间
        :param end_time 结束时间
        :param time_interval 时间间隔
        :return 对齐后数据列表
        """
        # 将 data_time 转换为 datetime 类型，并提取时间和数值
        times = [dev_data.data_time for dev_data in source_dev_data]

        aligned_times = []
        current_time = start_time
        while current_time <= end_time:
            aligned_times.append(current_time)
            current_time += time_interval

        aligned_dev_date = []
        for aligned_time in aligned_times:
            # 找出最接近 aligned_time 的原始数据点
            closest_idx = np.argmin([abs((t - aligned_time).total_seconds()) for t in times])
            dev_data_tmp = copy.deepcopy(source_dev_data[closest_idx])
            dev_data_tmp.data_time = aligned_time.strftime("%Y-%m-%d %H:%M:%S")
            aligned_dev_date.append(dev_data_tmp)
        return aligned_dev_date